package com.binance.sysconf.config;

import com.binance.master.old.config.OldDBConfig;
import com.binance.sysconf.mq.Obj2JsonMessageConverter;
import com.binance.sysconf.service.SysConfigVarCacheService;
import com.binance.sysconf.service.SysVarChangeReceiver;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import javax.sql.DataSource;

/**
 * Description: 系统变量加载自动配置类
 *
 * @author hongchaoMao - Date 2018/7/23
 */
@EnableRabbit
@Configuration
@AutoConfigureAfter(OldDBConfig.class)
public class SysConfigAutoConfigration{

    /**
     * 使用master-old中配置的pnk数据源
     * @param beanFactory Spring上下文
     */
    @Bean
    public JdbcTemplate oldJdbcTemplate(BeanFactory beanFactory) {
        DataSource dataSource = (DataSource)beanFactory.getBean("oldDataSource");
        return new JdbcTemplate(dataSource);
    }

    /**
     * 使用master-old中配置的pnk数据源
     * @param beanFactory Spring上下文
     */
    @Bean
    public NamedParameterJdbcTemplate oldNamedParameterJdbcTemplate(BeanFactory beanFactory) {
        DataSource dataSource = (DataSource)beanFactory.getBean("oldDataSource");
        return new NamedParameterJdbcTemplate(dataSource);
    }

    /**
     * 命名为messageConverter会被spring自动配置rabbitmq检测到并使用该消息转换器
     */
    @Bean
    public Obj2JsonMessageConverter messageConverter(){
        return new Obj2JsonMessageConverter();
    }

    @Bean(name = "sysConfigVarCacheService", initMethod = "init")
    public SysConfigVarCacheService sysConfigVarCacheService(
            @Qualifier("oldJdbcTemplate") JdbcTemplate oldJdbcTemplate){
        return new SysConfigVarCacheService(oldJdbcTemplate);
    }

    @Bean
    public SysVarChangeReceiver sysVarChangeReceiver(
            @Qualifier("sysConfigVarCacheService") SysConfigVarCacheService sysConfigVarCacheService){
        SysVarChangeReceiver receiver = new SysVarChangeReceiver();
        receiver.setSysConfigVarCacheService(sysConfigVarCacheService);
        return receiver;
    }

}

